<template lang="pug">
  div
    Upload.invisible(
      :action='action',
      name='files[]'
      accept='image/*'
      :format='["jpg", "jpeg", "png", "gif"]'
      :max-size='800'
      :data='{ folder: "uploads/body" }'
      :show-upload-list='false'
      :before-upload='onBeforeUpload',
      :on-success='onFileUploadSuccess'
      :on-format-error="handleFormatError"
      :on-exceeded-size="handleMaxSize"
    )
      div(ref='trigger') up
    quill-editor(
      ref='myQuillEditor',
      :content='content',
      :options='editorOptions',
      @ready='onEditorReady'
      @change='onEditorChange')
</template>

<script>

import { quillEditor } from 'vue-quill-editor'
import * as Quill from 'quill'

import http from '@/apis/http'

export default {
  components: {
    quillEditor
  },
  model: {
    prop: 'content',
    event: 'change'
  },
  props: {
    content: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      action: http.baseURL + 'fd/file/upload',
      sourceCodeMode: false,
      editorOptions: {
        theme: 'snow',
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              [{ 'header': 1 }, { 'header': 2 }],
              [{ 'color': [] }, { 'background': [] }],
              // [{ 'font': [] }],
              [{ 'align': [] }],
              ['image'],
              ['clean'],
              ['source']
            ],
            handlers: {
              'image': this.imgHandler,
              'source': this.sourceHandler
            },
            clipboard: {
              matchVisual: false
            }
          }
        }
      }
    }
  },
  computed: {
    editor () {
      return this.$refs.myQuillEditor.quill
    }
  },
  created () {
    this.srcEditor = document.createElement('textarea')
    this.srcEditor.style.cssText = 'width: 100%;margin: 0px;background: rgb(29, 29, 29);box-sizing: border-box;color: rgb(204, 204, 204);font-size: 15px;outline: none;padding: 20px;line-height: 24px;font-family: Consolas, Menlo, Monaco, &quot;Courier New&quot;, monospace;position: absolute;top: 0;bottom: 0;border: none;display:none'
  },
  methods: {
    onEditorReady () {
      this.editor.addContainer('ql-custom').appendChild(this.srcEditor)
      this.srcEditor.addEventListener('change', this.onEditorChange)
      // this.editor.on('text-change', (delta, oldDelta, source) => {
        // if (this.sourceCodeMode) return
      this.srcEditor.value = this.$refs.myQuillEditor.$el.children[1].children[0].innerHTML
      // })
    },
    // onEditorChange ({editor, html, text}) {
    onEditorChange (e) {
      // console.log('evt', e)
      if (this.sourceCodeMode) {
        this.$emit('change', e.target.value)
      } else {
        this.$emit('change', e.html)
      }
    },
    onBeforeUpload (file) {
      this.$Message.loading({
        content: '上传中',
        duration: 0
      })
    },
    onFileUploadSuccess (response, file, fileList) {
      // console.log(response)
      // console.log('file', file, fileList)
      let index = this.addRange !== null ? this.addRange.index : 0
      this.editor.insertEmbed(index, 'image', response.url, Quill.sources.USER)
      this.editor.formatText(index, 1, 'alt', response.name)
      this.editor.setSelection(index + 1, 0)
      this.$Message.destroy()
    },
    handleFormatError (file, fileList) {
      this.$Message.destroy()
      this.$Message.error('图片格式错误')
    },
    handleMaxSize (file, fileList) {
      this.$Message.destroy()
      this.$Message.error({
        content: '图片超出大小限制800k',
        duration: 3
      })
    },
    sourceHandler (state) {
      // console.log('src', state)
      this.sourceCodeMode = !this.sourceCodeMode
      if (!this.sourceCodeMode) {
        var html = this.srcEditor.value
        this.editor.clipboard.dangerouslyPasteHTML(html)
      }
      this.srcEditor.style.display = this.sourceCodeMode ? '' : 'none'
    },
    imgHandler (state) {
      this.addRange = this.editor.getSelection()
      if (state) {
        this.$refs.trigger.click()
      }
    }
  }

}
</script>

<style>
.ql-editor {
  min-height: 200px;
}
.ql-picker {
  z-index: 100;
}
.ql-source {
  /* width: 0 !important; */
  /* height: 0 !important; */
  padding: 0 !important;
  line-height: 1;
  outline: 0;
}
.ql-source:after {
  content: '[source]';
}
</style>
